package com.yc.vote.service.impl;

import com.yc.common.biz.BizException;
import com.yc.vote.entity.Items;
import com.yc.vote.entity.Vote;
import com.yc.vote.mapper.ItemsMapper;
import com.yc.vote.mapper.VoteMapper;
import com.yc.vote.service.IVoteService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.vote.util.MyBatisHelper;
import com.yc.vote.util.Utils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ly
 * @since 2022-07-03
 */
@Service
public class VoteServiceImpl extends ServiceImpl<VoteMapper, Vote> implements IVoteService {

    public void add(Vote vote) throws BizException {
        // 验证输入
        Utils.checkEmpty(vote.getVname(), "投票题目不能为空!");
        Utils.checkEmpty(vote.getVtype(), "投票类型不能为空!");
        Utils.checkEmpty(vote.getItems(), "投票选项不能为空!");
        Utils.check(vote.getItems().size() < 2, "投票选项数不能少于2!");
        for (int i = 0; i < vote.getItems().size(); i++) {
            Utils.checkEmpty(vote.getItems().get(i).getIname(), "第" + (i + 1) + "个选项不能为空!");
        }

        MyBatisHelper.exec( session->{
            VoteMapper voteMapper = session.getMapper(VoteMapper.class);
            ItemsMapper itemsMapper = session.getMapper(ItemsMapper.class);
            // 添加题目
            voteMapper.insert(vote);  // 获取了 id 值
            // 添加选项
            for (Items item : vote.getItems()) {
                item.setVid(vote.getId());
                itemsMapper.insert(item);
            }
        });
    }

    public List<Vote> queryAll(int page, int size){
        return MyBatisHelper.query(session->{
           VoteMapper mapper = session.getMapper(VoteMapper.class);
           int begin = (page - 1) * size;
           return mapper.selectAll(begin, size);
        });
    }

}
